package com.bbg.amyam.web.mvc;

import com.bbg.amyam.domain.model.Document;
import com.bbg.amyam.domain.model.ProfilePicture;
import com.bbg.amyam.web.util.image.ImageUtils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;

@RequestMapping("/profilepictures")
@Controller
@RooWebScaffold(path = "profilepictures", formBackingObject = ProfilePicture.class)
public class ProfilePictureController {

    private static final Log log = LogFactory.getLog(ProfilePictureController.class);

    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws ServletException {
        binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
    }

    @RequestMapping(value = "savedoc", method = RequestMethod.POST)
    public String createdoc(@Valid ProfilePicture document, BindingResult result, Model model, @RequestParam("content") MultipartFile content, HttpServletRequest request) {
        document.setFileType(content.getContentType());
        document.setFileName(content.getOriginalFilename());
        document.setDocId("doc" + String.valueOf(new Date().getTime()));
        document.setFileSize(content.getSize());
        try {
            document.setContent(ImageUtils.resizeImage(content, 300, 50));
        } catch (IOException e) {
            model.addAttribute("document", document);
            return "profilepictures/create";
        }
        if (result.hasErrors()) {
            model.addAttribute("document", document);
            return "profilepictures/create";
        }
        document.persist();
        return "redirect:/profilepictures?page=1&size=10" + encodeUrlPathSegment(document.getId().toString(), request);
    }

    @RequestMapping(value = { "/showdoc/{id}", "/showdoc/{id}/*" }, method = RequestMethod.GET)
    public String showdoc(@PathVariable("id") String id, HttpServletResponse response, Model model) {
        ProfilePicture doc = null;
        if (StringUtils.startsWith(id, "doc")) {
            List<Document> docList = ProfilePicture.findDocumentsByDocIdEquals(id).getResultList();
            if (docList.size() > 0) {
                doc = (ProfilePicture) docList.get(0);
            }
        } else {
            doc = ProfilePicture.findProfilePicture(Long.valueOf(id));
        }
        try {
            response.setHeader("Content-Disposition", "inline;filename=\"" + doc.getFileName());
            OutputStream out = response.getOutputStream();
            response.setContentType(doc.getFileType());
            IOUtils.copy(new ByteArrayInputStream(doc.getContent()), out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        ProfilePicture doc = ProfilePicture.findProfilePicture(id);
        doc.setDocURL("showdoc/" + id);
        uiModel.addAttribute("profilepicture", doc);
        uiModel.addAttribute("itemId", id);
        return "profilepictures/show";
    }

    @RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Long id, Model uiModel) {
        ProfilePicture doc = ProfilePicture.findProfilePicture(id);
        doc.setDocURL("profilepictures/showdoc/" + id);
        populateEditForm(uiModel, doc);
        return "profilepictures/update";
    }
}
